package com.yu.mall.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yu.mall.dto.PageDTO;
import com.yu.mall.dto.order.FreightDTO;
import com.yu.mall.dto.order.OrderDTO;
import com.yu.mall.dto.order.OrderQueryDTO;
import com.yu.mall.entity.Address;
import com.yu.mall.entity.Order;
import com.yu.mall.entity.OrderItem;
import com.yu.mall.entity.ProductInfo;
import com.yu.mall.entity.User;
import com.yu.mall.exception.ServiceException;
import com.yu.mall.mapStruct.order.OrderAdminVOChange;
import com.yu.mall.mapStruct.order.OrderDTOChange;
import com.yu.mall.mapStruct.order.OrderItemDTOChange;
import com.yu.mall.mapStruct.order.OrderItemVOChange;
import com.yu.mall.mapper.AddressMapper;
import com.yu.mall.mapper.OrderItemMapper;
import com.yu.mall.mapper.OrderMapper;
import com.yu.mall.mapper.ProductInfoMapper;
import com.yu.mall.mapper.ShoppingCartMapper;
import com.yu.mall.mapper.UserMapper;
import com.yu.mall.util.BeanHelper;
import com.yu.mall.util.JDUtils;
import com.yu.mall.util.ResultUtils;
import com.yu.mall.vo.PageResultVO;
import com.yu.mall.vo.ResultVO;
import com.yu.mall.vo.order.FreightVO;
import com.yu.mall.vo.order.OrderAdminVO;
import com.yu.mall.vo.order.OrderCrateVO;
import com.yu.mall.vo.order.OrderItemVO;
import com.yu.mall.vo.order.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@Transactional
@Slf4j
public class OrderService  {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderDTOChange orderDTOChange;

    @Autowired
    private OrderItemDTOChange orderItemDTOChange;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PayService payService;

    @Autowired
    private OrderItemVOChange orderItemVOChange;

    @Autowired
    private OrderAdminVOChange orderAdminVOChange;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    ProductInfoMapper productInfoMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    public ResultVO<FreightVO> getFreight(FreightDTO dto) throws ServiceException {
        Address address = addressMapper.selectByPrimaryKey(dto.getAddressId());
        dto.setProvinceId(address.getProvinceId());
        dto.setCityId(address.getCityId());
        dto.setCountyId(address.getCountyId());
        dto.setTownId(address.getTownId());
        String freight = JDUtils.getFreight(dto);
        FreightVO freightVO = JSON.parseObject(freight, FreightVO.class);
        return ResultUtils.success(freightVO);
    }

    @Transactional
    public ResultVO<String> crate(OrderDTO dto) throws ServiceException, InterruptedException {
        Address address = addressMapper.selectByPrimaryKey(dto.getAddressId());
        dto.setProvinceId(address.getProvinceId());
        dto.setCityId(address.getCityId());
        dto.setCountyId(address.getCountyId());
        dto.setTownId(address.getTownId());
        dto.setTownName(address.getTownName());
        dto.setProvinceName(address.getProvinceName());
        dto.setCityName(address.getCityName());
        dto.setCountyName(address.getCountyName());
        dto.setName(address.getName());
        dto.setPhone(address.getPhone());
        dto.setAddress(address.getAddress());

        log.info("订单入参：" + JSON.toJSONString(dto));
        boolean b = JDUtils.clickStock(dto);
        if(!b){
            return ResultUtils.error("商品无货");
        }

        String freight = JDUtils.getFreight(dto);
        FreightVO freightVO = JSON.parseObject(freight, FreightVO.class);
        Order order = orderDTOChange.toBean(dto);
        if(Objects.isNull(freightVO) || Objects.isNull(freightVO.getFreight()) || Objects.isNull(order.getFreight())){
            throw new ServiceException("未获取到运费");
        }
        if(freightVO.getFreight().compareTo(order.getFreight()) != 0){
            throw new ServiceException("运费有变化");
        }
        order.setFreight(freightVO.getFreight());

        String orderNo = System.currentTimeMillis() + "";
        order.setOrderNo(orderNo);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setStatus("1");
        BigDecimal orderPrice = new BigDecimal(0);
        List<OrderItem> orderItems = orderItemDTOChange.toBean(dto.getOrderItems());
        for (OrderItem orderItem : orderItems) {
            ProductInfo productInfo = productInfoMapper.selectByPrimaryKey(orderItem.getSkuId());
            if(productInfo == null || "1".equals(productInfo.getIsdel())){
                throw new ServiceException(orderItem.getName() + " 商品已删除");
            }
            if("2".equals(productInfo.getStatus())){
                throw new ServiceException(orderItem.getName() + " 商品已下架");
            }
            orderItem.setName(productInfo.getName());
            orderItem.setImagePath(productInfo.getImagePath());
            orderItem.setOrderId(order.getId());
            orderItem.setOrderNo(order.getOrderNo());
            Map<String, Object> priceMap = JDUtils.priceGetSellPrice(orderItem.getSkuId());
            if (!priceMap.isEmpty()) {
                JSONObject priceJson = ((JSONArray) priceMap.get("data")).getJSONObject(0);
                if(orderItem.getNum() <= 0){
                    throw new ServiceException(orderItem.getName() + " 数量不能小于1");
                }
                if(orderItem.getPrice().compareTo(priceJson.getBigDecimal("jdPrice")) != 0){
                    throw new ServiceException(orderItem.getName() + " 商品价格有变化");
                }
                orderPrice = orderPrice.add(orderItem.getPrice().multiply(new BigDecimal(orderItem.getNum())));
                orderItem.setJdPrice(priceJson.getBigDecimal("price"));
                orderItemMapper.insertSelective(orderItem);
                orderItem.setPrice(priceJson.getBigDecimal("price"));
            }
            if(!"".equals(orderItem.getShoppingId())&&orderItem.getShoppingId() !=null){
                shoppingCartMapper.deleteByPrimaryKey(orderItem.getShoppingId());
            }
        }

        order.setOrderPrice(orderPrice);
        order.setOrderPriceTotal(order.getOrderPrice().add(order.getFreight()));
        orderMapper.insertSelective(order);

        String s = JDUtils.submitOrder(order, orderItems, dto);
        JSONObject jsonObject = JSON.parseObject(s);
        String jdOrderId = jsonObject.getString("jdOrderId");
        BigDecimal jdOrderPrice = jsonObject.getBigDecimal("orderPrice");
        if(StringUtils.isBlank(jdOrderId)){
            Thread.sleep(500);
            jdOrderId = JDUtils.selectJdOrderIdByThirdOrder(orderNo);
            if(StringUtils.isBlank(jdOrderId)){
               throw new ServiceException("创建订单失败");
            }
        }
        Order order2 = new Order();
        order2.setId(order.getId());
        order2.setJdOrderNo(jdOrderId);
        order2.setJdOrderPrice(jdOrderPrice);
        order2.setJdOrderPriceTotal(jdOrderPrice.add(freightVO.getFreight()));
        orderMapper.updateByPrimaryKeySelective(order2);
        OrderCrateVO orderCrateVO = new OrderCrateVO();
        User user = userMapper.selectByPrimaryKey(dto.getOpenid());
        orderCrateVO.setBalance(user.getBalance());
        orderCrateVO.setOrderNo(order.getOrderNo());
        orderCrateVO.setOrderPriceTotal(order.getOrderPriceTotal());

        return ResultUtils.success(order.getOrderNo());
    }

    public ResultVO<List<OrderVO>> list(PageDTO dto, String name, String status) {
        PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        List<OrderVO> orderVOS = orderMapper.list(dto.getOpenid(),name,status);
        if(!CollectionUtils.isEmpty(orderVOS)){
            for (OrderVO orderVO : orderVOS) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderNo(orderVO.getOrderNo());
                List<OrderItem> list = orderItemMapper.select(orderItem);
                //List<OrderItemVO> orderItemVOS = orderItemVOChange.toVo(list);
                List<OrderItemVO> orderItemVOS = new ArrayList<>();
                for (OrderItem item : list) {
                    OrderItemVO vo = new OrderItemVO();
                    BeanHelper.copyProperties(item,vo);
                    orderItemVOS.add(vo);
                }
                int num = 0;
                for (OrderItemVO orderItemVO : orderItemVOS) {
                    num = num + orderItemVO.getNum();
                }
                orderVO.setTotalNum(num);
                orderVO.setOrderItems(orderItemVOS);
            }


        }
        return ResultUtils.success(orderVOS);
    }

    public PageResultVO<List<OrderAdminVO>> adminList(OrderQueryDTO dto) {
        PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        List<Order> orderVOS = orderMapper.adminList(dto);
        List<OrderAdminVO> orderAdminVOS = orderAdminVOChange.toVo(orderVOS);
        PageInfo pageInfo = new PageInfo<>(orderVOS);
        pageInfo.setList(orderAdminVOS);
        return ResultUtils.page(pageInfo);
    }
}
